package cqrtplm.aop;

import cn.hutool.core.collection.CollUtil;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import cqrtplm.constant.RTErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class RTDrawingDocAOP {

    @Resource
    private TyplmDocumentService typlmDocumentService;

    @Around(value = "execution(* com.hustcad.plm.pdm.iteration.service.TyplmIterationService.checkIn(..))")
    public Object checkDrawingAttributeAop(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        String docOid = (String) args[0];
        String typeDefName = (String) args[1];
        if(typeDefName.startsWith("ty.inteplm.doc.CTyDoc|DesignDrawings")){
            DocDetails docDetails = this.typlmDocumentService.queryDocDetails(new BigInteger(docOid), typeDefName);
            String version = docDetails.getVersion();
            if(version.startsWith("A")){
                return point.proceed();
            }
            if(ObjectUtils.isNotEmpty(docDetails)){
                Map<String, List<String>> ibaAttributeMap =
                        docDetails.getIbaAttributeMap();
                if(CollUtil.isEmpty(ibaAttributeMap) || !ibaAttributeMap.containsKey("ChangeDescription") || CollUtil.isEmpty(ibaAttributeMap.get("ChangeDescription")) || StringUtils.isEmpty(ibaAttributeMap.get("ChangeDescription").get(0)) || StringUtils.isBlank(ibaAttributeMap.get("ChangeDescription").get(0))){
                    throw RTErrorCodeEnum.DESCRIBE_RULE_ERROR.getException("变更描述为空，不允许检入！");
                }
            }
        }
        return point.proceed();
    }
}
